package com.android.happymall.fragment.member;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.happymall.R;
import com.android.happymall.fragment.BaseLazyFragment;
import com.android.happymall.model.member.CustomerQuestData;
import com.android.happymall.model.member.CustomerQuestDataCallback;
import com.android.happymall.model.member.MessageIndexData;
import com.android.happymall.model.member.MessageIndexDataCallback;
import com.android.happymall.model.member.MineMessageDetailData;
import com.android.happymall.model.member.MineMessageDetailDataCallback;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.HttpUtils;
import com.android.happymall.utils.MyLog;
import com.android.happymall.utils.ObjectUtils;
import com.android.happymall.view.recycleview.CustomLoadMoreView;
import com.android.happymall.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 我的消息
 * ---------------------------------------
 */
public class Fragment_Mine_Message extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;
    private View rootView;


    private static final String ARG_PARAM1 = "param1";

    private String mParam1;

    private LayoutInflater inflater;
    private FragmentActivity mcontext;
    private AlertDialog dialog;
    private SlideAdapter adapter;
    private int page = 1;
    private boolean networkConnected;
    private String Title = "" ;
    private String Content = "" ;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);

        }
    }

    public static Fragment_Mine_Message newInstance(String param1) {
        Fragment_Mine_Message fragment = new Fragment_Mine_Message();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 在onActivityCreated中调用的方法，可以用来进行初始化操作。
     */
    @Override
    protected void initPrepare() {
        initUI();
    }

    /**
     * fragment被设置为不可见时调用
     */
    @Override
    protected void onInvisible() {

    }

    /**
     * 这里获取数据，刷新界面
     */
    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            if(mParam1.equals("0")) {
                GetDataListData(page);
            }else
            {
                GetContentListData(page);
            }
        } else {

            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    /**
     * 初始化布局，请不要把耗时操作放在这个方法里，这个方法用来提供一个
     * 基本的布局而非一个完整的布局，以免ViewPager预加载消耗大量的资源。
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     */
    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        mcontext = getActivity();
        rootView = inflater.inflate(R.layout.fragment_mine_message, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    private void initUI() {
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new SlideAdapter(R.layout.item_list_mine_message, null);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                if(mParam1.equals("0")) {
                    //GetDetail(adapter.getData().get(position).getMid());
                }else {
                    Title = adapter.getData().get(position).getMessage_title();
                    Content = adapter.getData().get(position).getMessage_content();
                    showDialog();
                }


            }
        });
        //刷新
        Refresh();
    }
    private void showDialog() {
        LayoutInflater inflater = (LayoutInflater) mcontext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.dialog_detail_message, null);
        TextView dialog_sure = (TextView) v.findViewById(R.id.dialog_sure);
        TextView dialog_title = (TextView) v.findViewById(R.id.dialog_title);
        TextView dialog_tv = (TextView) v.findViewById(R.id.dialog_tv);
        dialog_title.setText(Title);
        dialog_tv.setText(Content);
        dialog_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog = new AlertDialog.Builder(mcontext).setView(v).setCancelable(true).show();
    }

    private void Refresh() {
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page = 1;
                    if(mParam1.equals("0")) {
                        GetDataListData(page);

                    }else
                    {
                        GetContentListData(page);
                    }

                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });

    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        if(mParam1.equals("0")) {
            GetDataListData(page);
        }else
        {
            GetContentListData(page);
        }
    }

    private boolean iszhankai;

    private class SlideAdapter extends BaseQuickAdapter<MessageIndexData.ListBean, BaseViewHolder> {


        public SlideAdapter(int layoutResId, List<MessageIndexData.ListBean> data) {
            super(layoutResId, data);

        }


        @Override
        protected void convert(BaseViewHolder helper, MessageIndexData.ListBean item) {
            helper.setText(R.id.item_consume_remark,item.getMessage_title());
            helper.setText(R.id.item_consume_time, item.getCreate_time());
        }


    }

    //获取消息具体数据
    private void GetDetail(String id) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERMESSAGEDETAIL ;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String, String> map = new HashMap<>();
            map.put("id",id);
            HttpUtils.get(address, header, map, new MineMessageDetailDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MineMessageDetailData response, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        if(response.getData().getTitle()!=null&&response.getData().getContent()!=null) {
                            Title = response.getData().getTitle();
                            Content = response.getData().getContent();
                            showDialog();
                        }
                    } else {
                        if(response.getCode() == 40001){
                            ObjectUtils.reLogin(mcontext);
                        }
                        noData.setVisibility(View.VISIBLE);
                    }


                }
            });
        } else {

            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mContext, "网络连接出现异常");
        }
    }


    //获取列表数据
    private void GetDataListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERMESSAGEINDEX + "?page=" + page;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HttpUtils.get(address, header, null, new MessageIndexDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(MessageIndexData response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        ArrayList<MessageIndexData.ListBean> listdata = new ArrayList<>();
                        if (response.getList() != null ) {
                            listdata.addAll(response.getList());
                            if (page == 1) {
                                adapter.setNewData(listdata);
                            } else {
                                adapter.addData(listdata);
                                adapter.loadMoreComplete();
                            }
                            if(response.getList().size()<10)
                            {
                                adapter.loadMoreEnd();
                            }
                        } else {
                            if(page==1)
                            {
                                noData.setVisibility(View.VISIBLE);
                            }
                            adapter.loadMoreEnd();
                        }
                    } else {
                        if(response.getCode() == 40001){
                            ObjectUtils.reLogin(mcontext);
                        }
                        noData.setVisibility(View.VISIBLE);
                    }


                }
            });
        } else {

            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mContext, "网络连接出现异常");
        }
    }

    //获取列表数据
    private void GetContentListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        String address = ConstantsUrl.domain +ConstantsUrl.MEMBER_CUSTOMER+ "?page=" + page;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> header = ObjectUtils.getHeader(mcontext);
            HashMap<String,String> map = new HashMap<>();
            map.put("page",page+"");
            map.put("catid","40");
            HttpUtils.get(address, header,map, new CustomerQuestDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(CustomerQuestData response, int id) {
                    mRefreshLayout.setRefreshing(false);
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        ArrayList<MessageIndexData.ListBean> listdata = new ArrayList<>();
                        if (response.getList() != null && response.getList().size() > 0) {
                            for(int i=0;i<response.getList().size();i++) {
                                listdata.add(new MessageIndexData.ListBean("", "", "", "", "最新公告",response.getList().get(i).getContent(), response.getList().get(i).getCreatetime()));
                            }
                            if (page == 1) {
                                adapter.setNewData(listdata);
                            } else {
                                adapter.addData(listdata);
                                adapter.loadMoreComplete();
                            }
                            if (response.getList().size() < 10) {
                                adapter.loadMoreEnd();
                            }
                        } else {
                            if (page == 1) {
                                noData.setVisibility(View.VISIBLE);
                            }
                            adapter.loadMoreEnd();
                        }
                    } else {
                        if (response.getCode() == 40001) {
                            ObjectUtils.reLogin(mcontext);
                        }
                        noData.setVisibility(View.VISIBLE);
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(mContext, "网络连接出现异常");
        }
    }
    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {
        ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
        page = 1;
        if(mParam1.equals("0")) {
            GetDataListData(page);
        }else
        {
            GetContentListData(page);
        }
    }


}

